/**
 * Copyright 厦门中软海晟信息技术有限公司 版权所有 违者必究 2019
 */
package com.leetCode._1_Array_Linked_List;

import com.leetCode.structure.ListNode;
import static com.leetCode.structure.ListNode.*;
/**
 * @author : sunzb(sunzb@hsit.com.cn)
 * @date: 2019/5/10
 */
//Medium
public class _02_24_SwapNodesInPairs {

    public static ListNode swapPairs(ListNode head) {
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }
        ListNode pair;
        ListNode pre = null;
        ListNode next;
        ListNode cur = head;
        ListNode result = head.next;
        while (cur != null) {
            pair = cur.next;
            if (pair == null) {
                break;
            }
            if (pre != null) {
                pre.next = pair;
            }
            next = pair.next;
            pair.next = cur;
            cur.next = next;
            pre = cur;
            cur = next;
        }
        return result;
    }

    public static void main(String[] args) {
        ListNode head = build(new int[]{1, 2, 3, 4});
        System.out.println(str(head));
        System.out.println(str(swapPairs(head)));
    }
}
